package microcredit.gui.handler;

import java.awt.Component;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import microcredit.model.Member;
import microcredit.model.MemberGroup;
import microcredit.model.MemberToGroup;
import microcredit.model.bo.BOMemberGroup;

public class MemberToGroupHandler extends AbstractHandler<MemberToGroup> {
	
	private final MemberGroup memberGroup;
	private final MemberHandler delegate;
	
	public MemberToGroupHandler(MemberGroup memberGroup, MemberHandler delegate) {
		super();
		this.delegate = delegate;
		this.memberGroup = memberGroup;
	}
	
	@Override
	public MemberToGroup newEntity(Component parent) throws Throwable {
		Member entity = delegate.newEntity(parent);
		if (entity != null) {
			List<MemberToGroup> groups = BOMemberGroup.create().assignMembersToGroup(Arrays.asList(entity), memberGroup);
			if (groups.size() > 0) {
				return groups.get(0);
			}
		}
		return null;
	}
	
	@Override
	public MemberToGroup open(Component component, MemberToGroup e)
			throws Throwable {
		Member m = delegate.open(component, e.getMember());
		if (m != null) {
			e.setMember(m);
			return e;
		}
		return null;
	}
	
	@Override
	public List<MemberToGroup> load() throws Throwable {
		if (memberGroup.getId() == null) {
			return Collections.emptyList();
		}
		return BOMemberGroup.create().readMemberToGroups(memberGroup.getId());
	}
	
	protected MemberToGroup convertTo(Member o) {
		List<MemberToGroup> groups = o.getMemberToGroups();
		if (groups != null && groups.size() > 0) {
			return groups.get(groups.size()-1);
		}
		return null;
	}

	@Override
	public void choose() throws Throwable {
		delegate.choose();
		super.choose();
	}
	
	@Override
	public void delete(MemberToGroup e) throws Throwable {
		BOMemberGroup.create().unassignMemberToGroup(e);
	}
	
	protected Member convertFrom(MemberToGroup o) {
		return o.getMember();
	}
	
}
